// 封装一个函数 连接数据库
import mysql from 'mysql2/promise'
import config from '../config/index.js';

// 线程池
const pool = mysql.createPool({
    host: config.database.HOST,
    user: config.database.USERNAME,
    password: config.database.PASSWORD,
    database: config.database.DATABASE,
    port: config.database.PORT
});

export const DataServices = {
    // 查询所有数据
    async query(sql, values) {
        try {
            // 通过线程池连接mysql
            const conn = await pool.getConnection();
            // 对连接执行某些操作
            const [rows, fields] = await conn.query(sql, values)
            // 释放连接
            pool.releaseConnection(conn);
            // 返回结果
            return Promise.resolve(rows);
        } catch (err) {
            return Promise.reject(err);
        }

    }
}

// 获取page详情页数据
export const getDetailData = () => {
    let _sql = `
    SELECT edu_data.*, user_info.avatar,user_info.username,user_info.type,user_info.sex
    FROM edu_data
    JOIN user_info ON edu_data.uid = user_info.id;
    `
    return DataServices.query(_sql)
}

// 获取教员信息服务
export const getTeacherData = (id) => {
    let _sql = `
    SELECT *
    FROM user_info
    WHERE id = "${id}";
    `
    return DataServices.query(_sql)
}


// 教员保存信息服务
export const saveTeacherData = (id, username, sex, colleage, specialized, address, subject, freeTime, expectedWages, certificate) => {
    let _sql = `
    UPDATE user_info
SET username = '${username}',
    sex = '${sex}',
    colleage = '${colleage}',
    specialized = '${specialized}',
    address = '${address}',
    subject = '${subject}',
    freeTime = '${freeTime}',
    expectedWages = '${expectedWages}',
    certificate = '${certificate}'
WHERE id = '${id}';
    `
    return DataServices.query(_sql)
}
